import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/user_model.dart';

/// 用户状态管理
class UserStore extends BaseViewModel with ReactiveServiceMixin {
  // 用户列表（模拟数据库）
  final List<UserModel> _users = [];

  // 当前登录用户
  UserModel? _currentUser;

  /// 获取当前登录用户
  UserModel? get currentUser => _currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => _currentUser != null;

  /// 初始化默认用户数据
  void initializeDefaultUsers() {
    _users.clear();
    _users.addAll(_getDefaultUsers());
  }

  /// 自动生成用户名
  String _generateUsername() {
    final adjectives = [
      'Swift',
      'Bold',
      'Bright',
      'Cool',
      'Fast',
      'Sharp',
      'Wild',
      'Free',
      'Pure',
      'True',
    ];
    final nouns = [
      'Runner',
      'Sprinter',
      'Jogger',
      'Athlete',
      'Champion',
      'Hero',
      'Star',
      'Light',
      'Wind',
      'Fire',
    ];

    final random = DateTime.now().millisecondsSinceEpoch;
    final adjective = adjectives[random % adjectives.length];
    final noun = nouns[random % nouns.length];
    final number = (random % 999) + 1;

    return '$adjective$noun$number';
  }

  /// 获取默认用户数据
  List<UserModel> _getDefaultUsers() {
    return [
      UserModel(
        id: '1',
        account: 'admin',
        password: '123456',
        username: 'Zephyr',
        signature: 'Running like the wind, unstoppable antelope',
        avatar: 'treasure_chest/images/avatar1.png',
      ),
      UserModel(
        id: '2',
        account: 'runner002',
        password: '123456',
        username: 'Nexus',
        signature: 'Pursuing speed and passion like a cheetah',
        avatar: 'treasure_chest/images/avatar2.png',
      ),
      UserModel(
        id: '3',
        account: 'runner003',
        password: '123456',
        username: 'Vortex',
        signature: 'Soaring eagle on the marathon road',
        avatar: 'treasure_chest/images/avatar3.png',
      ),
      UserModel(
        id: '4',
        account: 'runner004',
        password: '123456',
        username: 'Prism',
        signature: 'Running free on the track like a wild horse',
        avatar: 'treasure_chest/images/avatar4.png',
      ),
      UserModel(
        id: '5',
        account: 'runner005',
        password: '123456',
        username: 'Cipher',
        signature: 'Tough as a wolf, team-collaborating marathon warrior',
        avatar: 'treasure_chest/images/avatar5.png',
      ),
      UserModel(
        id: '6',
        account: 'runner006',
        password: '123456',
        username: 'Quantum',
        signature: 'Elegantly crossing the finish line like a dolphin',
        avatar: 'treasure_chest/images/avatar6.png',
      ),
      UserModel(
        id: '7',
        account: 'runner007',
        password: '123456',
        username: 'Matrix',
        signature: 'Polar bear on the marathon road with endless endurance',
        avatar: 'treasure_chest/images/avatar7.png',
      ),
      UserModel(
        id: '8',
        account: 'runner008',
        password: '123456',
        username: 'Phantom',
        signature: 'Runner leaping forward like a kangaroo',
        avatar: 'treasure_chest/images/avatar8.png',
      ),
      UserModel(
        id: '9',
        account: 'runner009',
        password: '123456',
        username: 'Zenith',
        signature: 'Penguin on the marathon road, team spirit first',
        avatar: 'treasure_chest/images/avatar9.png',
      ),
      UserModel(
        id: '10',
        account: 'runner010',
        password: '123456',
        username: 'Oracle',
        signature: 'Reaching every goal precisely like a carrier pigeon',
        avatar: 'treasure_chest/images/avatar10.png',
      ),
    ];
  }

  /// 用户登录
  Future<bool> loginUser(String account, String password) async {
    setBusy(true);
    try {
      // 模拟网络延迟
      await Future.delayed(const Duration(milliseconds: 500));

      final user = _users.firstWhere(
        (user) => user.account == account && user.password == password,
        orElse: () => throw Exception('User not found or incorrect password'),
      );

      _currentUser = user;
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 用户注册
  Future<bool> registerUser({
    required String account,
    required String password,
    String? signature,
    String? avatar,
  }) async {
    setBusy(true);
    try {
      // 模拟网络延迟
      await Future.delayed(const Duration(milliseconds: 500));

      // 检查账号是否已存在
      if (_users.any((user) => user.account == account)) {
        setError('Account already exists');
        return false;
      }

      // 自动生成用户名
      final username = _generateUsername();

      // 创建新用户
      final newUser = UserModel(
        id: (_users.length + 1).toString(),
        account: account,
        password: password,
        username: username,
        signature: signature ?? 'New marathon enthusiast',
        avatar: avatar ?? 'treasure_chest/images/avatar1.png',
      );

      _users.add(newUser);
      _currentUser = newUser;
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 退出登录
  void logoutUser() {
    _currentUser = null;
    notifyListeners();
  }

  /// 更新用户信息
  Future<bool> updateUserInfo({
    String? username,
    String? signature,
    String? avatar,
  }) async {
    setBusy(true);
    try {
      if (_currentUser == null) {
        setError('User not logged in');
        return false;
      }

      // 模拟网络延迟
      await Future.delayed(const Duration(milliseconds: 300));

      final updatedUser = _currentUser!.copyWith(
        username: username,
        signature: signature,
        avatar: avatar,
      );

      // 更新用户列表中的信息
      final index = _users.indexWhere((user) => user.id == _currentUser!.id);
      if (index != -1) {
        _users[index] = updatedUser;
      }

      _currentUser = updatedUser;
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 根据 ID 查询用户信息
  UserModel? getUserById(String userId) {
    try {
      return _users.firstWhere((user) => user.id == userId);
    } catch (e) {
      return null;
    }
  }

  /// 根据账号查询用户信息
  UserModel? getUserByAccount(String account) {
    try {
      return _users.firstWhere((user) => user.account == account);
    } catch (e) {
      return null;
    }
  }

  /// 获取所有用户列表
  List<UserModel> getAllUsers() {
    return List.from(_users);
  }

  /// 搜索用户
  List<UserModel> searchUsers(String keyword) {
    if (keyword.isEmpty) return [];

    return _users.where((user) {
      return user.username.toLowerCase().contains(keyword.toLowerCase()) ||
          user.signature.toLowerCase().contains(keyword.toLowerCase());
    }).toList();
  }
}
